<template>
  <view class="buy-wrapper">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <up-icon type="back" size="24" color="#333"></up-icon>
      </view>
      <text class="title">支付宝扫码支付</text>
    </view>

    <view class="pay-title">请使用支付宝扫码支付</view>
    <view class="qrcode-container" :class="{ expired: paymentStatus === 'EXPIRED' }">
      <canvas canvas-id="pay-qrcode" style="width: 300px; height: 300px; margin-bottom: 40rpx;" />
    </view>
    <view class="pay-amount">支付金额：￥{{ amount }}</view>

    <!-- 状态提示 -->
    <view class="status-message" v-if="paymentStatus === 'SUCCESS'">
      <text class="success-text">支付成功！正在跳转...</text>
    </view>
    <view class="status-message" v-if="paymentStatus === 'FAILED'">
      <text class="failed-text">支付失败，请重试</text>
    </view>
    <view class="status-message" v-if="paymentStatus === 'EXPIRED'">
      <text class="expired-text">支付已超时，请重新下单</text>
      <button class="back-btn" @click="goBack">返回</button>
    </view>
  </view>
</template>

<script setup>
import {ref, watch, onMounted, onUnmounted} from 'vue'
// import uQRCode from '../../uni_modules/cc-defineQRCode/components/cc-defineQRCode/common/uqrcode.js'
import {checkOrderStatus} from '@/apis/orderApi'

const qrCodeContent = ref('')
const amount = ref('')
const countdown = ref(180)
let timer = null
let pollTimer = null
const outTradeNo = ref('')
const paymentStatus = ref('PENDING')
const isLoading = ref(true)

// 生成二维码函数
const generateQRCode = () => {
  if (!qrCodeContent.value) {
    console.error('二维码内容为空，无法生成');
    uni.showToast({ title: '支付信息加载中...', icon: 'loading' });
    return;
  }

  uni.showLoading({ title: '生成二维码中', mask: true });

  uQRCode.make({
    canvasId: 'pay-qrcode',
    text: qrCodeContent.value,
    size: 300,
    margin: 10,
    success: () => {
      isLoading.value = false;
      uni.hideLoading();
    },
    fail: (err) => {
      console.error('二维码生成失败', err);
      uni.hideLoading();
      uni.showToast({ title: '二维码生成失败', icon: 'none' });

      // 3秒后重试
      setTimeout(generateQRCode, 3000);
    }
  });
};
// 页面加载完成后执行
onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options;

  // 解析URL参数（注意解码二维码）
  if (options.qrCode) {
    qrCodeContent.value = decodeURIComponent(options.qrCode);
  }
  if (options.amount) {
    amount.value = options.amount;
  }
  if (options.outTradeNo) {
    outTradeNo.value = options.outTradeNo;
  }

  console.log('接收参数:', {
    qrCode: qrCodeContent.value,
    amount: amount.value,
    outTradeNo: outTradeNo.value
  });

  // 确保参数获取后再生成二维码
  generateQRCode();
  startOrderPoll();
});


// 轮询订单状态
const startOrderPoll = () => {
  pollTimer = setInterval(() => {
    console.log('开始轮询订单状态:', outTradeNo.value)
    if (outTradeNo.value && countdown.value > 0 && paymentStatus.value === 'PENDING') {
      checkPaymentStatus()
    }
  }, 10000)
}
// 检查支付状态
const checkPaymentStatus = async () => {
  try {
    const res = await checkOrderStatus({outTradeNo: outTradeNo.value})
    console.log('订单状态响应:', res)
    if (res.data && res.data.code === 200) {
      const orderStatus = res.data.data.status
      if (orderStatus === 'SUCCESS') {
        clearInterval(timer)
        clearInterval(pollTimer)
        paymentStatus.value = 'SUCCESS'
        uni.showToast({title: '支付成功', icon: 'success'})

        setTimeout(() => {
          goBack()
        }, 1500)
      } else if (orderStatus === 'CLOSED' || orderStatus === 'FAILED') {
        clearInterval(timer)
        clearInterval(pollTimer)
        paymentStatus.value = 'FAILED'
      }
    }
  } catch (error) {
    console.error('查询订单状态失败:', error)
  }
}
// 返回上一页
const goBack = () => {
  uni.navigateTo({
    url: '/pages/transaction/transaction'
  })
}

// 页面卸载时清除定时器
onUnmounted(() => {
  if (timer) clearInterval(timer)
  if (pollTimer) clearInterval(pollTimer)
})

// 监听二维码内容变化，自动更新二维码
// 确保有值再监听变化
watch(() => qrCodeContent.value, (newVal) => {
  if (newVal) generateQRCode();
}, { immediate: true });
</script>

<style>
.header {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  position: relative;
  margin-bottom: 30rpx;
  width: 100%;
}

.back-btn {
  position: absolute;
  left: 0;
  padding: 10rpx;
}

.title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  font-weight: bold;
}

.buy-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20rpx;
  padding: 0 30rpx;
}

.pay-title {
  font-size: 36rpx;
  margin-bottom: 40rpx;
  color: #333;
}

.qrcode-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 40rpx;
  width: 100%;
}

.pay-amount {
  font-size: 36rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 30rpx;
}

.countdown-box {
  width: 100%;
  height: 80rpx;
  border: 2rpx solid #ff4500;
  border-radius: 40rpx;
  margin-top: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ff4500;
  font-size: 32rpx;
  background: #fff;
  margin-bottom: 40rpx;
}

/* 状态样式 */
.qrcode-container.expired canvas {
  opacity: 0.5;
  filter: grayscale(100%);
}

.status-message {
  text-align: center;
  margin-top: 30rpx;
}

.success-text {
  color: #07c160;
  font-size: 36rpx;
  font-weight: bold;
}

.failed-text {
  color: #ff4500;
  font-size: 36rpx;
  font-weight: bold;
}

.expired-text {
  color: #999;
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.back-btn {
  background-color: #07c160;
  color: #fff;
  border-radius: 50rpx;
  font-size: 32rpx;
  padding: 15rpx 60rpx;
  margin-top: 30rpx;
}
</style>